﻿
namespace VMWareLabWorkflowsDataContracts.VMWareLabDetailsDialogControls.Commands
{
    using System;
    using System.Reflection;
    using System.ComponentModel;

    using Microsoft.TeamFoundation.Build.Workflow.Activities;

    /// <summary>
    /// Opens the TestSpecListEditor inside the VMWare Lab Wizard
    /// </summary>
    public class TestSpecDialog
    {
        private Type testSpecEditor;
        private TypeConverter converter;
        private IServiceProvider serviceProvider;

        public TestSpecDialog()
        {
            Assembly assembly = Assembly.Load("Microsoft.TeamFoundation.Build.Controls, Version=11.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
            this.testSpecEditor = assembly.GetType("Microsoft.TeamFoundation.Build.Controls.TestSpecListEditor");
            this.serviceProvider = VMWareWizardData.VMWareWizzardDataInstance.ServiceProvider;
            this.converter = TypeDescriptor.GetConverter(typeof(TestSpecList));
        }

        public void ShowEditor()
        {
            if (this.testSpecEditor != null)
            {
                MethodInfo editValueMethod = this.testSpecEditor.GetMethod(
                    "EditValue", new[] { typeof(IServiceProvider), typeof(object) });
                var mParam = new object[]
                    {
                        this.serviceProvider,
                        VMWareWizardData.VMWareWizzardDataInstance.VMWareLabWorkflowDetails.AutomatedTestSettings.TestSpecList
                    };
                object classInstance = Activator.CreateInstance(this.testSpecEditor, null);
                try
                {
                    VMWareWizardData.VMWareWizzardDataInstance.VMWareLabWorkflowDetails.AutomatedTestSettings.TestSpecList = (TestSpecList)editValueMethod.Invoke(classInstance, mParam);
                }
                catch (Exception)
                {
                }
            }
        }

        public string GetTestSpecString()
        {
            try
            {
                if (converter != null && converter.CanConvertTo(typeof(string)) && VMWareWizardData.VMWareWizzardDataInstance.VMWareLabWorkflowDetails.AutomatedTestSettings.TestSpecList != null)
                    return converter.ConvertToString(VMWareWizardData.VMWareWizzardDataInstance.VMWareLabWorkflowDetails.AutomatedTestSettings.TestSpecList);
            }
            catch (Exception) { }
            return string.Empty;
        }
    }
}
